<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once('Entity/Members_Entity.php');        
class Members_Model extends Members_Entity
{  
    public function __construct()
    {
        parent::__construct();
    }
    
    public function resetpass($id, $pass)
    {
        $this->setId($id);
        $this->setPass($pass);
        $this->save();
    }
    
    public function checkMemberIsActive($email)
    {
        $sql = "SELECT id, status FROM members WHERE email = ? ";
        $query = $this->db->query($sql, array($email));
        $obj = $query->row();
        if ($obj) {
            return $obj;
        } else {
            return (object)array('status' => -1);
        }
    }
    
    public function checkMember($email)
    {
        $sql = "SELECT id FROM members WHERE email = ? ";
        $query = $this->db->query($sql, array($email));
        $obj = $query->row();
        if ($obj) {
            return true;
        }
        return false;
    }
    
    public function checkFormSigup()
    {
        $this->form_validation->set_rules('txtEmail', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('txtPassword', 'Mật khẩu', 'trim|required|min_length[6]|matches[txtConPassword]');
        $this->form_validation->set_rules('txtConPassword', 'Xác nhận mật khẩu', 'trim|required');
        $this->form_validation->set_rules('txtFullName', 'Họ tên', 'trim|required');
        $this->form_validation->set_rules('day', 'Ngày', 'trim|required');
        $this->form_validation->set_rules('month', 'Tháng', 'trim|required');
        $this->form_validation->set_rules('year', 'Năm', 'trim|required');
        $this->form_validation->set_rules('sltEducation', 'Trình độ học vấn', 'trim|required');
        $this->form_validation->set_rules('major', 'Ngành nghề', 'trim|required');
        $this->form_validation->set_rules('otherMajor', 'Ngành nghề khác', 'trim');
        $this->form_validation->set_rules('city', 'Tỉnh thành', 'trim|required');
        $this->form_validation->set_rules('otherCity', 'Tỉnh thành khác', 'trim');
        $this->form_validation->set_rules('ckbAgree', 'ckbAgree', 'trim|required');

        return $this->form_validation->run();
    }
    
    public function Active($memberId)
    {
        $this->setId($memberId);
        $this->setStatus(1);
        $this->setCreated(time());
        $this->save();
    }
    
    public function addNewMember()
    {
        $this->load->helper('text');
        $this->load->model('Members_Activecode_Model');
        $this->setEmail($this->input->post('txtEmail'));
        $this->setName($this->input->post('txtFullName'));
        $this->setStatus(0);
        $dateofbirth = $_POST['year'].'-'.$_POST['month'].'-'.$_POST['day'];
        $this->setDateofbirth($dateofbirth);
        $this->setSid($this->input->post('sltEducation'));
        $this->setJid($this->input->post('major'));
        $this->setJother($this->input->post('otherMajor'));
        $this->setPid($this->input->post('city'));
        $this->setPother($this->input->post('otherCity'));
        $pass = $this->input->post('txtPassword');  
        $pass = imd5(trim($pass));  
        $this->setPass($pass);
        $mid = $this->save();
        if ($mid) {
           $actiModel = new Members_Activecode_Model();
           $actiModel->addNewActiveCode($mid); 
        }
        return $mid;
    }
    

    public function login($email, $pass)
    {
        $sql = "SELECT * FROM members WHERE email = ? AND pass = ? ";
        $query = $this->db->query($sql, array($email, $pass));
        return $query->row();
    }    

    
    // -------- Admin
    
     public function dataSort($field, $order)
    {
      $xOrder =  $order == 'asc' ? 'desc' : 'asc';
      $img = $order == 'desc' ? '<img src=\'/data/admin/down.jpg\' />' : ' <img src=\'/data/admin/up.jpg\' />';  
      $url = anchor('members/sort/'.$field.'/'.$xOrder, t($field).$img);
      $_SESSION['sm_sort_members'] = array('field' => $field, 'order' => $order, 'url' => $url);
    }
    
    public function dataIndex($target)
    {
      $numshow = 25;
      $this->db->select('members.id, members.email, members.name, members.status, members.dateofbirth, educations.title as sid_type, jobs.title as jid_type, provinces.title as pid_type, members.created');
      $this->db->from('members');
      
        $this->db->join('educations', 'members.sid = educations.id');
        $this->db->join('jobs', 'members.jid = jobs.id');
        $this->db->join('provinces', 'members.pid = provinces.id');
       
        if ($this->session->userdata('sm_filter_educations'))
            $this->db->where('members.sid', $this->session->userdata('sm_filter_educations')); 
        if ($this->session->userdata('sm_filter_jobs'))
            $this->db->where('members.jid', $this->session->userdata('sm_filter_jobs')); 
        if ($this->session->userdata('sm_filter_provinces'))
            $this->db->where('members.pid', $this->session->userdata('sm_filter_provinces'));
      if ($this->session->userdata('sm_find_members')) {
        $this->db->like('members.name', $this->session->userdata('sm_find_members'));
      }
      if (isset($_SESSION['sm_sort_members'])) {
        $sort = $_SESSION['sm_sort_members'];
        $this->db->order_by('members.'.$sort['field'], $sort['order']);
       }
      else {  
        $this->db->order_by('members.created', 'desc');
      }
      $this->db->limit($numshow, $target);
      $query = $this->db->get();
      $paging = paging_admin('members/index', $this->_total(), $numshow, 4);
      return array('query'=>$query, 'paging'=>$paging,'fil_educations' => $this->Filter_educations(), 'fil_jobs' => $this->Filter_jobs(), 'fil_provinces' => $this->Filter_provinces(),                    
                  'formFind' => $this->formFind());
    }
          
    private function cbo_educations($id = 0)
    {
        $this->load->helper("form");
        $query = $this->db->get("educations");
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $sl = $id == 0 ? set_value("sid") : $id;
        return form_dropdown("sid", $options, $sl);
    }
        
    private function cbo_jobs($id = 0)
    {
        $this->load->helper("form");
        $query = $this->db->get("jobs");
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $sl = $id == 0 ? set_value("jid") : $id;
        return form_dropdown("jid", $options, $sl);
    }
        
    private function cbo_provinces($id = 0)
    {
        $this->load->helper("form");
        $query = $this->db->get("provinces");
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $sl = $id == 0 ? set_value("pid") : $id;
        return form_dropdown("pid", $options, $sl);
    }
    
    private function _total()
    {
        return $this->db->count_all_results("members"); 
    }
    
    private function _checkmembersById($id)
    {
        $query = $this->db->get_where("members", array("id" => $id));
        if ($query->num_rows() > 0) return true;
        else {
            notify_set_messages(notify_atten(t("Record không tồn tại")), "members");
            return false;
        }
    }
    
    private function formFind()
    {
        $this->load->helper('form');
        $attributes = array('name' => 'frmFind', 'id' => 'frmFind');
        $f = form_open(site_url('members/find'), $attributes);
        $data = array('name' => 'txt_find', 'id' => 'txt_find', 'value' => '', 'style' => 'width:200px');
        $f .= form_input($data);
        $s = array('name' => 'submit', 'value' => t('Find'), 'class' => 'ibutton green', 'style' => 'margin-left:10px');
        $f .= form_submit($s);
        if ($this->session->userdata('sm_find_members')) {
            $r = array('name' => 'btnReset', 'value' => 'Reset', 'class' => 'ibutton red', 'style' => 'margin-left:10px');
            $f .= form_submit($r);
        } 
        $f .= form_close();
        return $f;
    }
    
    private function Filter_educations()
    {
        $this->load->helper('form');
        $query = $this->db->get('educations');
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $id = !$this->session->userdata('sm_filter_educations') ? 0 : $this->session->userdata('sm_filter_educations');
        $attributes = array('name' => 'frmFiltereducations', 'id' => 'frmFiltereducations');
        $f = form_open(site_url('members/filtereducations'), $attributes);
        $f .= form_dropdown('sid', $options, $id);
        $data = array('name' => 'btnFiltereducations', 'class' => 'ibutton green', 'style' => 'margin-left:10px', 'value' => t('Filter'));
        $f .= form_submit($data);
        if ($this->session->userdata('sm_filter_educations')) {
            $r = array('name' => 'btnReset', 'class' => 'ibutton red', 'style' => 'margin-left:10px', 'value' => 'Reset');  
            $f .= form_submit($r); 
        }
        $f .= form_close();
        return $f;
    }
    
    private function Filter_jobs()
    {
        $this->load->helper('form');
        $query = $this->db->get('jobs');
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $id = !$this->session->userdata('sm_filter_jobs') ? 0 : $this->session->userdata('sm_filter_jobs');
        $attributes = array('name' => 'frmFilterjobs', 'id' => 'frmFilterjobs');
        $f = form_open(site_url('members/filterjobs'), $attributes);
        $f .= form_dropdown('jid', $options, $id);
        $data = array('name' => 'btnFilterjobs', 'class' => 'ibutton green', 'style' => 'margin-left:10px', 'value' => t('Filter'));
        $f .= form_submit($data);
        if ($this->session->userdata('sm_filter_jobs')) {
            $r = array('name' => 'btnReset', 'class' => 'ibutton red', 'style' => 'margin-left:10px', 'value' => 'Reset');  
            $f .= form_submit($r); 
        }
        $f .= form_close();
        return $f;
    }
    
    private function Filter_provinces()
    {
        $this->load->helper('form');
        $query = $this->db->get('provinces');
        foreach ($query->result() as $row) {
            $options[$row->id] = $row->title;
        }
        $id = !$this->session->userdata('sm_filter_provinces') ? 0 : $this->session->userdata('sm_filter_provinces');
        $attributes = array('name' => 'frmFilterprovinces', 'id' => 'frmFilterprovinces');
        $f = form_open(site_url('members/filterprovinces'), $attributes);
        $f .= form_dropdown('pid', $options, $id);
        $data = array('name' => 'btnFilterprovinces', 'class' => 'ibutton green', 'style' => 'margin-left:10px', 'value' => t('Filter'));
        $f .= form_submit($data);
        if ($this->session->userdata('sm_filter_provinces')) {
            $r = array('name' => 'btnReset', 'class' => 'ibutton red', 'style' => 'margin-left:10px', 'value' => 'Reset');  
            $f .= form_submit($r); 
        }
        $f .= form_close();
        return $f;
    }
    
    
    public function dataEdit($id)
    {
        if (!$this->_checkmembersById($id)) return redirect(site_url('members'));
        $query = $this->db->get_where('members',array('id' => $id));
        return array('query' => $query,
                    'cbo_educations' => $this->cbo_educations($query->row('sid')), 
                    'cbo_jobs' => $this->cbo_jobs($query->row('jid')), 
                    'cbo_provinces' => $this->cbo_provinces($query->row('pid'))
                    );
    }
    
    public function dataAdd()
    {
        return array('cbo_educations' => $this->cbo_educations(), 'cbo_jobs' => $this->cbo_jobs(), 'cbo_provinces' => $this->cbo_provinces());
    }
    
    public function checkForm()
    {
        $this->form_validation->set_rules('email', t('email'),'trim|required');
        $this->form_validation->set_rules('name', t('name'),'trim|required');
        $this->form_validation->set_rules('pass', t('pass'),'trim');
        $this->form_validation->set_rules('status', t('status'),'trim');
        $this->form_validation->set_rules('dateofbirth', t('dateofbirth'),'trim|required');
        $this->form_validation->set_rules('sid', t('sid'),'trim|required|integer');
        $this->form_validation->set_rules('jid', t('jid'),'trim|required|integer');
        $this->form_validation->set_rules('jother', t('jother'),'trim');
        $this->form_validation->set_rules('pid', t('pid'),'trim|required|integer');
        $this->form_validation->set_rules('pother', t('pother'),'trim');
        $this->form_validation->set_rules('created', t('created'),'trim|required');
        return $this->form_validation->run();
    } 
    
    public function doUpdate()
    {
        $this->load->helper('text');
        $this->setEmail($this->input->post('email'));
        $this->setName($this->input->post('name'));
        if ($this->input->post('pass') != '') {
           $this->setPass(imd5($this->input->post('pass'))); 
        }
        $time = strtotime($this->input->post('created'));
        $this->setStatus($this->input->post('status'));
        $this->setDateofbirth($this->input->post('dateofbirth'));
        $this->setSid($this->input->post('sid'));
        $this->setJid($this->input->post('jid'));
        $this->setJother($this->input->post('jother'));
        $this->setPid($this->input->post('pid'));
        $this->setPother($this->input->post('pother'));
        $this->setCreated($time);
            
        if (isset($_POST['idx'])) {
            $id = decrypt($_POST['idx']);
            $this->setId($id);
        }
        
        return $this->save();
    }
}